package config

import (
	"github.com/BurntSushi/toml"
	"github.com/Unixeno/TheMoon/common/constants"
	"os"
)

type CoreConfig struct {
	ConfigFilename string
	NodeID         string
	LogLevel       string

	StartLink StartLinkConfig
	Zone      ZoneConfig
}

type StartLinkConfig struct {
	// 心跳包时间，默认值10秒
	Heartbeat int32
	// 客户端连接超时时间，默认值30秒
	HandshakeTimeout int32
	// 读取超时时间，默认值15秒
	ReadDeadline int32
	// 发送超时时间，默认值15秒
	WriteDeadline int32
	// 客户端类型
	ClientType string
	// 服务端地址
	Server string
	// 服务端ID
	PlanetID string
	// 证书ca文件路径
	CAFile string
	// 证书文件路径
	CertFile string
	// 证书私钥路径
	PrivateKeyFile string
}

type ZoneConfig struct {
	ApiPath            string
	DefaultNetwork     string
	DefaultNetworkName string
}

var SysConfig = newBasicConfig()

func Init() error {
	filename := os.Getenv("CONFIG_PATH")
	if filename != "" {
		SysConfig.ConfigFilename = filename
	}
	return SysConfig.Parse()
}

func newBasicConfig() *CoreConfig {
	return &CoreConfig{
		ConfigFilename: "./moon.toml",
		LogLevel:       "debug",
		StartLink: StartLinkConfig{
			Heartbeat:        constants.DefaultHeartbeat,
			HandshakeTimeout: constants.DefaultHandshakeTimeout,
			ReadDeadline:     constants.DefaultReadDeadline,
			WriteDeadline:    constants.DefaultWriteDeadline,
			ClientType:       constants.DefaultClientType,
			Server:           constants.DefaultServer,
			PlanetID:         constants.DefaultPlanetID,
			CAFile:           "cert/ca.pem",
			CertFile:         "cert/moon.pem",
			PrivateKeyFile:   "cert/moon.key",
		},
		Zone: ZoneConfig{
			ApiPath:            constants.DefaultIslandsApi,
			DefaultNetwork:     constants.DefaultNetwork,
			DefaultNetworkName: constants.DefaultNetworkName,
		},
	}
}

func (c *CoreConfig) Parse() error {
	_, err := toml.DecodeFile(c.ConfigFilename, c)
	return err
}
